﻿Imports System.Windows.Forms
Imports NPOI.SS.UserModel
Imports NPOI.XSSF.UserModel
Imports NPOI.HSSF.UserModel
Imports Client.Upload
Imports Sy.Data

Public Class Frm_ImportClient
    Private Property ThreadExecutor_ImportClient As Sy.Threading.ThreadExecutor
    Private ReadOnly Log As New LogSub(Sub(m) Txt_Log.AppendLogOnThreadAsync(m))
    Private Sub TitleBar1_ClickClose(sender As Object, e As FormClosingEventArgs) Handles TitleBar1.ClickClose
        If ThreadExecutor_ImportClient.IsNotNull() AndAlso ThreadExecutor_ImportClient.IsAlive Then
            Sy.UI.Form.MsgBox.Show(ThreadExecutor_ImportClient.CurAbortThreadMsg,
                                   {"停止", "继续"},
                                   "退出警告",
                                   Me,
                                   {Sub()
                                        ThreadExecutor_ImportClient.Abort()
                                    End Sub,
                                    Sub()
                                        e.Cancel = True
                                    End Sub})
        End If
    End Sub

    Private Sub Btn_Floder_Click(sender As Object, e As EventArgs) Handles Btn_Floder.Click
        Dim ofd As New OpenFileDialog With {
                        .InitialDirectory = Sy.Environment.Path.Desktop,
                        .Filter = "Excel File|*.xls;*.xlsx"
                    }
        If ofd.ShowDialog = DialogResult.OK Then
            Txt_Path.Text = ofd.FileName
            Btn_Import.Enabled = True
        End If
    End Sub

    Private Sub Btn_Import_Click(sender As Object, e As EventArgs) Handles Btn_Import.Click
        ThreadExecutor_ImportClient.IsNull(Function()
                                               Dim t = New Sy.Threading.ThreadExecutor With {
                                                               .ApartmentState = Threading.ApartmentState.STA
                                                           }
                                               Return t
                                           End Function)
        ThreadExecutor_ImportClient.Execute(
            Sub()
                Dim FileName = Txt_Path.Text
                If IO.File.Exists(FileName) Then
                    '读取文件内容
                    Log("正在读取用户数据...")
                    Dim Clients As List(Of Request)
                    Try
                        Using fs = New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read)
                            Dim filetype = IO.Path.GetExtension(FileName).ToLower()
                            Dim IWorkbook As IWorkbook
                            If filetype.Equals(".xlsx") Then
                                IWorkbook = New XSSFWorkbook(fs)
                            ElseIf filetype.Equals(".xls") Then
                                IWorkbook = New HSSFWorkbook(fs)
                            Else
                                Log($"读取文件失败,无法识别文件格式![{filetype}]")
                                Exit Sub
                            End If
                            Clients = ReadExcelClient(IWorkbook)
                        End Using
                        If Clients.IsNotNull() AndAlso Clients.Count > 0 Then
                            Log("正在上报用户数据")
                            '获取初始化ID
                            Dim InitApi As New Init.Init("")
                            If Not InitApi.Post(Log) Then
                                Log("读取文件失败,失败原因:获取初始化数据失败!")
                            End If
                            For Each ClientItem In Clients
                                ClientItem.BlockId = InitApi.Response.BlockId
                                Dim Api As New PostClient(ClientItem)
                                If Api.Post(Log) Then
                                    Log($"{ClientItem.Name}上报成功!")
                                Else
                                    Log($"{ClientItem.Name}上报失败!")
                                End If
                            Next
                            Log("所有用户上报结束")
                        End If
                    Catch ex As Exception
                        Log($"读取用户数据失败!失败原因:{ex.Message}")
                    End Try
                End If
            End Sub, "读取用户数据")
    End Sub
    Private Function ReadExcelClient(IWorkbook As IWorkbook) As List(Of Request)
        Dim Clients As New List(Of Request)
        Try
            Dim sheet = IWorkbook.GetSheetAt(0)
            Dim rows = sheet.GetRowEnumerator()
            While rows.MoveNext
                Dim row As IRow = rows.Current
                If row.RowNum < 1 Then
                    Continue While
                End If
                Dim name = row.GetCell(0), mobile = row.GetCell(1),
                    email = row.GetCell(2), companyTel = row.GetCell(3),
                    job = row.GetCell(4), linkedIn = row.GetCell(5)
                Dim nameStr = If(name.IsNull(), "", name.ToString()),
                    mobileStr = If(mobile.IsNull(), "", mobile.ToString()),
                    emailStr = If(email.IsNull(), "", email.ToString()),
                    companyTelStr = If(companyTel.IsNull(), "", companyTel.ToString()),
                    jobStr = If(job.IsNull(), "", job.ToString()),
                    linkedInStr = If(linkedIn.IsNull(), "", linkedIn.ToString())
                Dim OneCLient As New Request(nameStr, mobileStr, emailStr.ToString(), Client.ClientSource.ExternalImport, companyTelStr, jobStr, linkedInStr)
                Clients.Add(OneCLient)
            End While
        Catch ex As Exception
            Log($"读取文件异常,原因:{ex.Message}")
            Return Null
        End Try
        Log($"读取文件完成,共读取[{Clients.Count}]个用户")
        Return Clients
    End Function
End Class